<?php
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}


class small_wx extends CI_Controller
{
    private $APPID = 'wx0b0963e402f7a01f';
    private $APPSECRET = '4f296a8947a6649c6d8bcbe21399812e';
    private $MID = '1413996802';
    private $APPKEY = 'BPZMHdhFbo6UJ8yBhAFeTnSAF7U9tWu7';

    /**
     * @function 获取openid
     */
    function getCode()
    {
        $code = $this->input->get('code');

        if ($code == '') {
            echo json_encode(array('code' => 9000, 'msg' => 'code不能为空'));
        } else {
            $da = array();
            $a = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=wx0b0963e402f7a01f&secret=4f296a8947a6649c6d8bcbe21399812e&js_code=' . $code . '&grant_type=authorization_code');
            $access_token = json_decode($a, true);

            //判断用户是否存在
            $data = $this->db->select('mid')->get_where('member', array('openid_xcx' => $access_token['openid']))->result_array();

            if (count($data) > 0) {
                $da['mid'] = $data[0]['mid'];
                $da['status'] = 0;
            } else {
                if (!empty($access_token['openid'])) {
                    $this->db->insert('member', array('openid_xcx' => $access_token['openid']));
                    $da['mid'] = $this->db->insert_id();
                    $da['status'] = 1;
                } else {
                    echo json_encode(array('code' => 9000, 'msg' => '非法code'));
                    exit;
                }
            }
            echo json_encode(array('code' => 1000, 'data' => $da));
            exit;
        }
    }

    /**
     * @function 用户信息
     */
    function getUserInfo()
    {
        try {

            $mid = $this->input->post('mid');

            if (!empty($mid)) {
                echo json_encode(array('code' => 9000, 'msg' => '参数错误'));
                exit();
            }

            $da['nickname'] = $this->input->post('nickName');
            $da['sex'] = $this->input->post('gender');
            $da['city'] = $this->input->post('city');
            $da['country'] = $this->input->post('country');
            $da['province'] = $this->input->post('province');
            $da['headimgurl'] = $this->input->post('avatarUrl');

            $da['tj_mid'] = $this->config->item('tj_mid');
            $da['subscribe_time'] = mktime();
            $da['subscribe'] = 1;

            $this->db->where('mid', $mid)->update('member', $da);

            echo json_encode(array('code' => 1000, 'msg' => '信息保存成功'));
            exit;
        } catch (Exception $e) {
            echo json_encode(array('code' => 9000, 'msg' => $e->getMessage()));
            exit;
        }
    }

    /**
     * @function 保存用户聊天信息
     */
    function chat()
    {
        try {
            $from_uid = $this->input->post('from_uid');
            $to_uid = $this->input->post('to_uid');
            $msg = $this->input->post('msg');

            $min = min($from_uid, $to_uid);
            $max = max($from_uid, $to_uid);

            $room_id = $min . '-' . $max;

            $this->db->insert('xcx_chat_room', array('from_uid' => $from_uid, 'to_uid' => $to_uid, 'msg' => $msg, 'room_id' => $room_id));

            echo json_encode(array('code' => 1000, 'msg' => '聊天记录保存成功'));
            exit;

        } catch (Exception $e) {
            echo json_encode(array('code' => 1000, 'msg' => $e->getMessage()));
        }
    }

    /**
     * @function 获取聊天记录
     */
    function getChatInfo()
    {
        $room_id = $this->input->post('room_id');
        $offset = $this->input->post('offset');

        $chat = $this->db->query("select * from `pan_xcx_chat_room` WHERE room_id = $room_id ORDER  BY  id DESC  limit $offset,10")->result_array();

        if (count($chat) > 0) {
            echo json_encode(array('code' => 1000, 'msg' => '获取聊天记录成功', 'data' => array('chat' => $chat, 'offset' => $offset + 10)));
        } else {
            echo json_encode(array('code' => 9000, 'msg' => '获取聊天记录失败'));
        }
    }

    /**
     * @function 统一下单
     */
    function do_pay()
    {
        $this->output->enable_profiler(TRUE);
        $mid = $this->input->post('mid');

        $data = $this->db->select('openid_xcx')->get_where('member', array('mid' => $mid))->result_array();
        if (count($data) > 0) {
            $openid_xcx = $data[0]['openid_xcx'];
        } else {
            echo json_encode(array('code' => 9000, 'msg' => '用户ID不存在'));
            exit;
        }

        $xml = $this->createXml(array('openid_xcx' => $openid_xcx));
        $data = $this->postXmlCurl($xml, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
        $xml = simplexml_load_string($data, NULL, LIBXML_NOCDATA);
        $array = json_decode(json_encode($xml), true);

        if ($array['return_code'] == 'SUCCESS') {
            $signStr = 'appId=' . $array['appid'] . '&nonceStr=' . $array['nonce_str'] . '&package=prepay_id=' . $array['prepay_id'] . '&signType=MD5&timeStamp=' . time() . '&key=' . $this->APPKEY;
            $paySign = md5($signStr);

            echo json_encode(array(
                'code' => 1000,
                'data' => array(
                    'timeStamp' => time(),
                    'nonceStr' => $array['nonce_str'],
                    'package' => 'prepay_id=' . $array['prepay_id'],
                    'signType' => 'MD5',
                    'paySign' => $paySign
                )
            ));

        } else {
            echo json_encode(array('code' => 9000, 'msg' => $array['return_msg']));
        }
        //$paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111) = 22D9B4E54AB1950F51E0649E8810ACD6
    }

    function notify()
    {
        //接受POST数据
        $post_xml = $this->input->post();
        //微信支付成功，返回回调地址url的数据：XML转数组Array
        $xml = simplexml_load_string($post_xml, NULL, LIBXML_NOCDATA);
        $post_data = json_decode(json_encode($xml), true);
        $postSign = $post_data['sign'];
        unset($post_data['sign']);

        /* 微信官方提醒：
         *  商户系统对于支付结果通知的内容一定要做【签名验证】,
         *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
         *  防止数据泄漏导致出现“假通知”，造成资金损失。
         */
        ksort($post_data);// 对数据进行排序
        //对数组数据拼接成key=value字符串
        $str = $this->ToXml($post_data);
        //再次生成签名，与$postSign比较
        $user_sign = strtoupper(md5($post_data));

        $where['out_trade_no'] = $post_data['out_trade_no'];
        //$order_status = M('home_order', 'xxf_witkey_')->where($where)->find();

        if ($post_data['return_code'] == 'SUCCESS' && $postSign) {

        }
    }

    /**
     * @function  给微信发送确认订单金额和签名正确，SUCCESS信息
     */
    function return_success()
    {
        $return['return_code'] = 'SUCCESS';
        $return['return_msg'] = 'OK';
        $xml_post = '<xml>
                          <return_code>' . $return['return_code'] . '</return_code>
                          <return_msg>' . $return['return_msg'] . '</return_msg>
                         </xml>';
        echo $xml_post;
        exit;
    }

    /**
     *    作用：以post方式提交xml到对应的接口url
     */
    public
    function postXmlCurl($xml, $url, $second = 30)
    {
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOP_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            echo 0;
            exit;
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    /**
     *    作用：设置标配的请求参数，生成签名，生成接口参数xml
     */
    function createXml($data = array())
    {
        //公众账号ID
        $parameter["appid"] = $this->APPID;
        //商户号
        $parameter["mch_id"] = $this->MID;
        //随机字符串
        $parameter["nonce_str"] = $this->createNoncestr();
        //商品描述
        $parameter['body'] = '小妖会馆小程序';
        //商户订单号
        $parameter['out_trade_no'] = time();
        //总金额
        $parameter['total_fee'] = 1;
        //通知地址
        $parameter['notify_url'] = 'https://lpsp.coralxt.com/app/small_wx/notify';
        //客户端IP
        $parameter['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
        //用户openid
        $parameter['openid'] = $data['openid_xcx'];
        //支付类型
        $parameter['trade_type'] = 'JSAPI';
        //签名
        $parameter["sign"] = $this->getSign($parameter);

        return $this->ToXml($parameter);
    }

    /**
     *    作用：产生随机字符串，不长于32位
     */
    public
    function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     *    作用：array转xml
     */
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";

            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";

        return $xml;
    }

    /**
     *    作用：array转xml
     */
    function ToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        }
        $xml .= "</xml>";

        return $xml;
    }

    /**
     *    作用：生成签名
     */
    public
    function getSign($jsApiObj)
    {
        foreach ($jsApiObj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //   echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->APPKEY;
        //  echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //   echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //   echo "【result】 ".$result_."</br>";
        return $result_;
    }


    /**
     *    作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

}